<template>
  <main-content title="订单管理">
    <template #tab-bar>
      <el-radio-group v-model="currentFilter" @change="handleFilterChange">
        <el-radio-button plain style="margin-bottom: 4px;" :label="item.value" v-for="(item, index) in filterList"
          :key="index">{{
            `${item.label}（${item.count}）` }}
        </el-radio-button>
      </el-radio-group>
    </template>

    <template #search-bar>
      <SearchBar inline :block="true">
        <template #normal>
          <el-form-item label="订单号">
            <el-input v-model="form.orderNo" clearable placeholder="搜索订单号" />
          </el-form-item>
          <el-form-item label="用户ID">
            <el-input v-model="form.userId" clearable placeholder="搜索用户ID" />
          </el-form-item>
          <el-form-item label="客户唯一标识">
            <el-input v-model="form.unionId" clearable placeholder="搜索客户唯一标识" />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker v-model="orderTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
              :default-time="defaultTime1" />
          </el-form-item>
          <el-form-item label="冻结状态">
            <el-select v-model="form.freezeFlag">
              <el-option :value="null" label="全部"></el-option>
              <el-option :value="1" label="已冻结"></el-option>
              <el-option :value="0" label="已解冻"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品规格名称">
            <el-input v-model="form.productName" clearable placeholder="搜索商品规格名称" />
          </el-form-item>
        </template>
        <template #advantage>
          <el-form-item label="商品名称">
            <el-input v-model="form.title" clearable placeholder="搜索商品名称" />
          </el-form-item>
          <el-form-item label="商品类型">
            <el-select v-model="form.goodsType" placeholder="搜索商品类型" clearable>
              <el-option :label="option.label" :value="option.value" v-for="(option, index) in merchantProductTypes"
                :key="index" />
            </el-select>
          </el-form-item>
          <el-form-item label="充值账号">
            <el-input v-model="form.rechargeAccount" clearable placeholder="输入充值账号" />
          </el-form-item>
          <el-form-item label="商家">
            <el-select v-model="form.storeId" filterable clearable placeholder="选择商家">
              <el-option v-for="item in storeList" :key="item.id" :label="item.storeName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户手机号">
            <el-input v-model="form.userPhone" clearable placeholder="搜索客户手机号" />
          </el-form-item>
          <el-form-item label="订单来源">
            <el-input v-model="form.detail" clearable placeholder="输入订单来源" />
          </el-form-item>

          <!--          <ins-cascader-filter @change="(value) => form.queryInsIds = value"></ins-cascader-filter>-->
        </template>
        <template #button>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>

            <!-- TODO 加权限 -->
            <el-button type="primary" @click="showExportData = true">导出</el-button>

            <!-- 冻结订单操作 -->
            <el-dropdown class="cus-select" split-button type="primary" @click="openFreeze('batch', '冻结订单')"
              @command="openFreeze($event, '解冻订单')">
              批量冻结
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="batch">
                    批量解冻
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    <LayoutTable ref="tokensManage" url="/extensions/merchant/order/pageOrder" :setSearch="setSearch" disable-auto-height
      :param="{ ...form, ...businessData, status: status }" @selection-change="handleSelectionChange" :rowKey="(row: any) => {
        return String(row.id);
      }
        " :row-class-name="tableRowClassName">
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column prop="orderNo" label="订单号" width="280" />
      <el-table-column label="用户ID" min-width="180">
        <template #default="{ row }">
          <span v-if="row.user">{{ row.user.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户唯一标识" min-width="180">
        <template #default="{ row }">
          <span v-if="row.user">{{ row.user.unionId }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="scope">
          {{ getOrderStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180">
        <template #default="scope">
          {{ dateFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="payOfMoney" label="支付金额" width="150">
        <template #default="scope">
          <div>
            {{ `${scope.row.payOfCurrencyCount || 0}积分+${setMoneyConfig(scope.row.payOfMoney)}` }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品规格名称" prop="productName" width="200"></el-table-column>
      <el-table-column prop="goodsType" label="商品类型" width="120">
        <template #default="scope">
          {{ getProductType(scope.row.goodsType) }}
        </template>
      </el-table-column>
      <el-table-column label="充值号码" width="150"> <template #default="{ row }">
          {{ row.ext?.rechargeAccount ?? '' }}
        </template></el-table-column>
      <el-table-column prop="title" label="商品名称" width="180" />
      <el-table-column label="商家名称" prop="storeName" width="150"></el-table-column>
      <el-table-column prop="userPhone" label="客户手机号" width="150" />
      <el-table-column label="订单来源" prop="detail" width="200"></el-table-column>
      <el-table-column label="所属应用" prop="businessType" width="150">
        <template #default="props">
          {{ getBusinessTypeLabel(props.row.businessType) }}
        </template>
      </el-table-column>

      <!-- <el-table-column prop="userPhone" label="客户手机号" width="150" /> -->

      <!-- <el-table-column prop="payOfCurrencyCount" label="支付积分" width="120" />
      <el-table-column prop="payOfMoney" label="支付金额" width="150">
        <template #default="scope">
          <div>
            {{ setMoneyConfig(scope.row.payOfMoney) }}
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button link type="primary" @click="goOrderDetail(scope.row)" v-has="['08040101']">
            查看订单
          </el-button>
          <span v-if="scope.row.status == 2 && ['cardPassword', 'recharge'].includes(scope.row.goodsType)"
            style="margin-left:4px">
            <el-button link type="primary" @click="freezeOrder(scope.row)" v-if="scope.row.freezeFlag == 0">
              冻结订单
            </el-button>
            <el-button link type="primary" v-if="scope.row.freezeFlag == 1" @click="unfreezeOrder(scope.row)"
              style="color:#14b8a3">
              解冻订单
            </el-button>
          </span>
        </template>
      </el-table-column>
    </LayoutTable>
    <exportData v-model:show-dialog="showExportData" :search-data="{ ...form, ...businessData }" title="订单管理-商城"
      export-type="orderInfoExport" :time-key="orderTime" :time-field="['createStartTime', 'createEndTime']">
    </exportData>
    <FreezeOrderForm v-model="freezeDialog" :title="freezeDialogTitle" @confirm-handle="confirmFreeze"
      @close="closeFreeze" :mode="freezeType" :id="currentRow?.id ?? ''" />
  </main-content>
</template>
<script lang="ts">
export default {
  name: "MallOrderList",
};
</script>
<script lang="ts" setup>
import moment from "moment";

import { IOrderPageRow } from "@/api/modules/pointsMall";
import { getStoreInfos } from "@/api/system";
// import { ApiResult, PaginatePayload } from "@/api/base/ApiResult";

import { getOrderStatics, orderFreeze, orderUnfreeze, orderFreezeBatch, orderUnfreezeBatch } from "@/api/pointsMall";
import { dateFormat } from "@/utils/filters";
import { getRecentWeekTime } from "@/utils/getRecentWeekTime";
import { orderStatus, merchantProductTypes } from "@/config/dictionary";
import { setMoneyConfig } from "@/utils";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import { useBusinessType } from "@/views/order/compositions/useBusinessType";
import exportData from "@/components/exportData/exportData.vue";
import FreezeOrderForm from "@/components/order/FreezeOrderForm.vue";
const { mallConfig } = useMallConfig();
// import {IOrderPageData, IOrderPageRow} from "@/api/modules/pointsMall";
// import { getOrderList } from "@/api/pointsMall";
// import { orderStatus, productTypes } from "@/config/dictionary";
const tokensManage = ref()
const router = useRouter();
const { getBusinessTypeLabel } = useBusinessType();
const showExportData = ref(false);
const setSearch = ref(Number());
// const currentOperateRow = ref({} as IOrderPageRow);
// const logisticsInfoDialogVisible = ref(false);
const currentFilter = ref("0,2,3,4,5,6,7,9,10,11");
// const businessTypeData = ref({
//   mall: "商城",
//   activity: "活动",
// });
const filterList = ref([
  {
    label: "全部订单",
    value: "0,2,3,4,5,6,7,9,10,11",
    count: 0,
  },
  {
    label: "待审核",
    value: 11,
    count: 0,
  },
  {
    label: "待支付",
    value: 0,
    count: 0,
  },

  {
    label: "待提货",
    value: 2,
    count: 0,
  },

  {
    label: "待发货",
    value: 3,
    count: 0,
  },
  {
    label: "待收货",
    value: 4,
    count: 0,
  },
  {
    label: "已完成",
    value: 5,
    count: 0,
  },
  {
    value: 6,
    label: "已关闭",
    count: 0,
  },
  {
    value: 7,
    label: "提货失败",
    count: 0,
  },
  {
    label: "待发货:请求失败",
    value: 9,
    count: 0,
  },
  {
    label: "待发货:请求成功",
    value: 10,
    count: 0,
  },
]);

const storeList = ref([]);
const getStoreList = async () => {
  const merchantId = store.state.user.merchantId;
  const rs = await getStoreInfos({ merchantId });
  if (rs.code === 200) {
    storeList.value = rs.payload;
  }
};
const orderTime = ref("" as any);
//添加默认一周下单时间
orderTime.value = [getRecentWeekTime().startTime, getRecentWeekTime().endTime]
const businessData = reactive({
  businessType: "mall",
  businessId: mallConfig.value.id,
});
const status = ref('')
const form = reactive({
  orderNo: "",
  userPhone: "",
  startTime: null,
  endTime: null,
  goodsName: null,
  goodsType: "",
  title: "",
  createStartTime: getRecentWeekTime().startTime,
  createEndTime: getRecentWeekTime().endTime,
  queryInsIds: [],
  freezeFlag: null,
  unionId: "",
  rechargeAccount: '',
  productName: "",
  storeId: "",
  withExtOrder: true,
  userId:""
});
watch(form, () => {
  getOrderStaticsList()
})

const currentRow = ref(null)
const freezeType = ref('')
const freezeDialog = ref(false)
const freezeDialogTitle = ref('')
const openFreeze = (type: string, title: string) => {
  freezeType.value = type
  if (type == 'batch') {
    if (!selections.value.length) {
      return ElMessage.warning('至少选择一条数据！')
    }
    if (selections.value.every(i => i.status !== 2)) {
      tokensManage.value.clearSelection()
      return ElMessage.warning('操作失败,只能操作待提货订单哦～')
    }

  }
  freezeDialogTitle.value = title
  freezeDialog.value = true
}
const selections = ref([])
const handleSelectionChange = (val: any) => {
  selections.value = val
}

const defaultTime1 = reactive([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]); // '12:00:00', '08:00:00'

watch(orderTime, (val) => {
  /* ... */
  if (val) {
    form.createStartTime = String(new Date(val[0]).getTime());
    form.createEndTime = String(new Date(val[1]).getTime());
  } else {
    form.createStartTime = "";
    form.createEndTime = "";
  }
});
const getOrderStaticsList = async () => {
  filterList.value.forEach(i => i.count = 0)
  console.log("[ 11 ]", 11);
  let rs: any = await getOrderStatics({ ...businessData, ...form });
  if (rs.code === 200) {
    rs.payload?.forEach((item: { count: number; status: any }) => {
      filterList.value.forEach((el) => {
        if (
          item.status == el.value ||
          (item.status == "-1" && el.value == "0,2,3,4,5,6,7,9,10,11")
        ) {
          el.count = item.count;
        }
      });
    });
  }
};

const handleFilterChange = (radioValue: any) => {
  if (Number(radioValue) === -1) {
    status.value = "";
  } else {
    status.value = radioValue;
  }
};

const getOrderStatus = (status: number) => {
  return orderStatus.find((item) => item.value === status)?.label ?? "--";
};

const getProductType = (_productType: number) => {
  return (
    merchantProductTypes.find((item) => item.value == String(_productType))
      ?.label ?? _productType
  );
};

const goOrderDetail = (row: IOrderPageRow) => {
  router.push({
    path: `/mall/order/list/orderdetail`,
    query: {
      id: row.id,
    },
  });
};
const onSearch = () => {
  setSearch.value++;
};

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getOrderStaticsList();
    getStoreList();
  },
  {
    deep: true,
  }
);

//冻结订单
const freezeOrder = async (row: any) => {
  currentRow.value = row
  openFreeze('single', '冻结订单')

}
//解冻订单
const unfreezeOrder = async (row: any) => {
  currentRow.value = row
  openFreeze('single', '解冻订单')
}


//解冻/冻结订单
const confirmFreeze = async (form: { reason: string }) => {
  if (freezeType.value == 'single') {
    if (freezeDialogTitle.value == '冻结订单') {
      const res = await orderFreeze({ id: currentRow.value.id, content: form.reason })
      if (res.code == 200) {
        ElMessage.success('操作成功！')
        freezeDialog.value = false
        onSearch()
        freezeType.value = ''
        currentRow.value = null

      }
    }
    if (freezeDialogTitle.value == '解冻订单') {
      const res = await orderUnfreeze({ id: currentRow.value.id, content: form.reason })
      if (res.code == 200) {
        ElMessage.success('操作成功！')
        freezeDialog.value = false
        onSearch()
        freezeType.value = ''
        currentRow.value = null
      }
    }
  }

  if (freezeType.value == 'batch') {
    const ids = selections.value.map(i => i.id)
    if (freezeDialogTitle.value == '冻结订单') {
      const res = await orderFreezeBatch({ ids: ids, content: form.reason })
      if (res.code == 200) {
        ElMessage.success('操作成功！')
        freezeDialog.value = false
        onSearch()
        freezeType.value = ''
        tokensManage.value.clearSelection()
      }
    }
    if (freezeDialogTitle.value == '解冻订单') {
      const res = await orderUnfreezeBatch({ ids: ids, content: form.reason })
      if (res.code == 200) {
        ElMessage.success('操作成功！')
        freezeDialog.value = false
        onSearch()
        freezeType.value = ''
        tokensManage.value.clearSelection()
      }
    }
  }
}

const closeFreeze = () => {
  freezeDialog.value = false
  currentRow.value = null
  tokensManage.value.clearSelection()
}
const tableRowClassName = ({ row }) => {
  if (row.freezeFlag == 1) {
    return "blue-row"
  }
  return ""
}

onBeforeMount(() => {
  getOrderStaticsList();
  getStoreList();
});
</script>
<style lang="scss">
.el-table .blue-row {
  --el-table-tr-bg-color: #e4e9ff;
}
</style>
<style lang="scss" scoped>
.table-wrapper {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.cus-select {
  margin-left: 12px;

  :deep(.el-dropdown__caret-button) {
    margin-left: -4px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
</style>
